package DBUtil;

import user.entity.User;

import java.sql.*;
//数据库辅助类
public class Dbutil {
    public static Connection conn=null;
    public static PreparedStatement prep=null;
    public static ResultSet rs=null;
    
 //通用增删改
public static boolean Update(String sql,String[] ShuJu){
    try {
        prep=IStatement(sql,ShuJu);
        int count= prep.executeUpdate();
        if(count>0)
            return true;
        else return false;}
    catch (SQLException e) {
        e.printStackTrace();
    }catch (Exception e){
        e.printStackTrace();
    }finally{
        closes(null,prep,conn);
    }
    return false;
}
    //关闭资源
    public static void closes(ResultSet rs, PreparedStatement prep, Connection conn) {
    if(rs!=null) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(prep!=null){
        try {
            prep.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(conn!=null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    }
    //获取数据库操作对象
    private static PreparedStatement IStatement(String sql, String[] ShuJu)throws Exception {
    prep= getConnections().prepareStatement(sql);
    if(ShuJu!=null){
        for(int i=0;i< ShuJu.length;i++)
        prep.setString(i+1,ShuJu[i]);
    }
    return prep;
    }
    //注册驱动，获取连接
    public static Connection getConnections() throws Exception{
                Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/enroll_1","root","ymh652185");
    }
    //查询
    public static ResultSet query(String sql,String ShuJu,String num){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/enroll_1", "root", "ymh652185");
            prep = conn.prepareStatement(sql);
            if(ShuJu!=null)
            prep.setObject(1, ShuJu);
            if(num!=null)
                prep.setString(2,num);
            rs = prep.executeQuery();
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
